<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/1/3
 * Time: 12:40
 */
class Wechat extends MY_View_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->config->load('wechat');
        $data = $this->config->item('wechat');
        $data['redirect_url'] = site_url('auth/wechat');
        $this->load->library('Wechat_login',$data);
    }

    /**
     * 微信登陆
     * PC:  url?client=browser
     * wechat: url
     */
    public function index()
    {
        $code = isset($_GET['code'])? $_GET['code']: false;
        if (!$code) {
            $this->load->helper('string');
            $state = random_string();
            $_SESSION['state'] = $state;
            if (isset($_GET['client']) && $_GET['client'] == 'browser') {
                $scope = 'snsapi_login';
            } else {
                $scope = 'snsapi_userinfo';
            }
            $login_url = $this->wechat_login->create_login_url('', $scope,$state);
            header("Location: " . $login_url, TRUE, 301);
            exit;
        } else {
            $state = isset($_GET['state'])? $_GET['state']: '';
            if (empty($state) or $state!=$_SESSION['state'] or $state!=$_SESSION['state'].'browser') {
                show_error('微信登录错误!state错误');
            }
            $token = $this->wechat_login->get_access_token($code, $state);
            $token  = (array) json_decode($token);
            if ($token['errcode'] != 0) {
                show_error($token['errmsg']);
            }
            if(!$token['openid']) {
                show_error('openid 参数错误');
            }
            $url = site_url() . '/auth/wechat/login?openid='
                . $token['openid'] . '&access_token='
                . $token['access_token'] . '&refresh_token='
                . $token['refresh_token'] . '&state='
                . $state;
            Header("HTTP/1.1 301 See Other");
            Header("Location: $url");
            exit;
        }
    }

    /**
     * 授权登录操作
     */
    public function login()
    {
        $gets = $this->input->get();
        if (!isset($gets['openid']) || !$gets['openid']) {
            show_error('微信登录错误!appid为空');
        }
        if (!isset($gets['access_token']) || !$gets['access_token']) {
            show_error('微信登录错误!openid获取失败');
        }

        if (strpos($gets['state'], 'browser') !== false) {
            $openid = '';
        } else  {
            $openid = $gets['openid'];
        }

        $user_info = $this->wechat_login->get_user_info($gets['access_token'], $gets['openid']);
        $user_info = (array) json_decode($user_info);
        /**
         * openid, nickname,sex,city:Chaoyang,province:Beijing,county:CN
         * headimgurl,unionid
         */
        $this->load->model('auth/Users');
        $this->load->model('auth/User_wechat');
        $user_id = $this->User_wechat->get_user_by_wechat($user_info['openid'], $user_info['unionid']);
        if (!$user_id) {
            $username = preg_replace("/[^a-zA-Z0-9\x80-\xff_]+/", "", $user_info['nickname']);
            if (strlen($username) == 0) {
                $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $username = substr(str_shuffle(str_repeat($pool, 5)), 0, 6);
            }
            $username = $username.random_string('numeric', 4);

            //无用户，创建用户
            switch($user_info['sex']){
                case '1':
                    $gender = 1;
                    break;
                case '2':
                    $gender = 0;
                    break;
                default:
                    $gender = -1;
            }

            $extend = array(
                'avatar'                =>  $user_info['headimgurl'],
                'nickname'				=>	$user_info['nickname'],
                'gender'				=>	$gender,
                'address'				=>	$user_info['province'].$user_info['city'],
                'from'					=>	'wechat',
            );
            $user = $this->auth_nuan->create_user_third($username, '111111', $extend);
            $wechat_info = array(
                'user_id'               =>  $user['user_id'],
                'wechat_unionid'		=>  isset($user_info['unionid'])? $user_info['unionid']: '',
                'wechat_openid'			=>  $openid,
                'wechat_refresh_token'	=>	$gets['refresh_token'],
                'wechat_auth_time'		=>	date("Y-m-d H:i:s"),
                'wechat_auth_num'		=>	0
            );
            $this->User_wechat->insert($wechat_info);
            $error = $this->auth_nuan->get_error_message();
            if ($error) {
                foreach ($error as $key => $msg) {
                    show_error($msg);
                }
            }
            $user['id'] = $user['user_id'];
        }
        $user = $this->Users->get_user_by_id($user_id['user_id']);
        if (is_object($user)) {
            $user = (array) $user;
        }
        $this->auth_nuan->set_logged_session($user);
        $this->auth_nuan->create_autologin($user['id']);
        redirect(site_url());
    }
}